// utils/price_calculator.js

/**
 * 根据时间范围和分时段定价计算总价
 * @param {string} startTime - 开始时间 'HH:mm'
 * @param {string} endTime - 结束时间 'HH:mm'
 * @param {Array} timeBasedPricing - 分时段定价规则
 * @param {number} defaultHourlyPrice - 默认小时单价
 * @returns {number} - 计算出的总价
 */
function calculatePrice(startTime, endTime, timeBasedPricing, defaultHourlyPrice) {
  if (!timeBasedPricing || timeBasedPricing.length === 0) {
    return calculatePriceByHour(startTime, endTime, defaultHourlyPrice);
  }

  const priceMap = createPriceMap(timeBasedPricing, defaultHourlyPrice);
  
  const start = new Date(`1970-01-01T${startTime}:00`);
  let end = new Date(`1970-01-01T${endTime}:00`);

  if (end <= start) {
    end.setDate(end.getDate() + 1);
  }

  let totalPrice = 0;
  const totalMinutes = (end - start) / 60000;
  const startMinuteOfDay = start.getHours() * 60 + start.getMinutes();

  for (let i = 0; i < totalMinutes; i++) {
    const currentMinuteOfDay = (startMinuteOfDay + i) % (24 * 60);
    const pricePerMinute = priceMap[currentMinuteOfDay];
    totalPrice += pricePerMinute;
  }

  return Math.round(totalPrice * 100) / 100;
}

/**
 * 创建分钟级价格映射表
 * @param {Array} timeBasedPricing - 分时段定价规则
 * @param {number} defaultHourlyPrice - 默认小时单价
 * @returns {Object} - 分钟 -> 价格 的映射
 */
function createPriceMap(timeBasedPricing, defaultHourlyPrice) {
  const priceMap = {};
  const defaultMinutePrice = defaultHourlyPrice / 60;

  // 初始化所有分钟为默认价格
  for (let i = 0; i < 24 * 60; i++) {
    priceMap[i] = defaultMinutePrice;
  }

  // 应用分时段定价
  for (const slot of timeBasedPricing) {
    const slotStart = parseInt(slot.start_time.split(':')[0]) * 60 + parseInt(slot.start_time.split(':')[1]);
    const slotEnd = parseInt(slot.end_time.split(':')[0]) * 60 + parseInt(slot.end_time.split(':')[1]);
    const pricePerMinute = slot.price / 60;

    for (let m = slotStart; m < slotEnd; m++) {
      priceMap[m] = pricePerMinute;
    }
  }
  return priceMap;
}

/**
 * 按小时计算价格
 * @param {string} startTime - 开始时间 'HH:mm'
 * @param {string} endTime - 结束时间 'HH:mm'
 * @param {number} hourlyPrice - 小时单价
 * @returns {number} - 总价
 */
function calculatePriceByHour(startTime, endTime, hourlyPrice) {
  const start = startTime.split(':');
  const end = endTime.split(':');
  const startHour = parseInt(start[0]);
  const startMinute = parseInt(start[1]);
  const endHour = parseInt(end[0]);
  const endMinute = parseInt(end[1]);

  let duration = (endHour - startHour) + (endMinute - startMinute) / 60;
  if (duration < 0) {
    duration += 24; // 处理跨天的情况
  }

  let price = duration * hourlyPrice;
  return Math.round(price * 100) / 100;
}

module.exports = {
  calculatePrice,
  calculatePriceByHour
};